<template>
  <view>
    <leave_note />
    <view class="price-box flex_p_20">
      <uv-form :model="form" ref="formRef" :rules="rules" labelWidth="110px" errorType="border-bottom">
        <uv-form-item label="报价人" prop="priceUserStr" borderBottom required>
          <uv-input v-model="form.priceUserStr" placeholder="请输入报价人" inputAlign="right" disabled border="none" disabledColor="transparent" >
          </uv-input>
        </uv-form-item>
        <uv-form-item label="联系方式" prop="priceUserPhone" borderBottom required>
          <uv-input v-model="form.priceUserPhone" placeholder="请输入联系方式" inputAlign="right" disabled border="none" disabledColor="transparent" >
          </uv-input>
        </uv-form-item>
        <uv-form-item label="报价金额(元)" prop="price" borderBottom required>
          <uv-input v-model="form.price" placeholder="请输入报价金额" inputAlign="right" border="none" disabledColor="#fff" >
          </uv-input>
        </uv-form-item>
        <uv-form-item label="备注信息" borderBottom>
          <uv-input v-model="form.priceRemark" placeholder="请输入备注信息" inputAlign="right" border="none" disabledColor="#fff" >
          </uv-input>
        </uv-form-item>
        <uv-form-item label="报价图片" borderBottom>
          <view class="flex_1 flex flex_x_end">
            <view style="width: 180rpx;">
              <uv-upload
                  :fileList="fileList1"
                  name="1"
                  :maxCount="1"
                  @afterRead="afterRead"
                  @delete="deletePic"
              ></uv-upload>
            </view>
          </view>
        </uv-form-item>
        <uv-form-item label="报价文件" borderBottom>
          <view class="flex_1 flex flex_x_end">
            <view style="width: 180rpx;">
              <uv-upload
                  :fileList="fileList2"
                  name="2"
                  accept="all"
                  :maxCount="1"
                  @afterRead="afterReadOther"
                  @delete="deletePicOther"
              ></uv-upload>
            </view>
          </view>
        </uv-form-item>
      </uv-form>
      <view class="flex_h_50"></view>
      <view class="flex_1 flex_p_lr">
        <uv-button type="primary" color="#2D4C98" shape="circle" @click="submitForm">确认提交</uv-button>
      </view>
    </view>
    <view class="flex_h_25"></view>
  </view>
</template>

<script>
import Leave_note from "@/components/leave_note.vue";
import config from "@/config";
import {getToken, getUserInfoId} from "@/utils/auth";
import PriceApi from "@/api/price/price";
import UserInfoApi from "@/api/system/userInfo";

export default {
  components: {Leave_note},
  data() {
    return {
      userId: null,
      baseURL: config.baseUrl,
      linkId: null,
      form: {
        id: null,
        price: null,
        priceUserPhone: null,
        priceUserId: null,
        priceUserStr: null,
        priceRemark: null,
        priceImg: null,
        priceFiles: null,
        priceVideo: null,
      },
      rules: {
        price: [{
          required: true,
          message: '请输入报价金额',
          trigger: 'blur'
        }],
        priceUserPhone: [{
          required: true,
          message: '请输入联系方式',
          trigger: 'blur'
        }],
        priceUserStr: [{
          required: true,
          message: '请输入报价人',
          trigger: 'blur'
        }]
      },
      fileList1: [],
      upImg: [],
      fileList2: [],
      upFiles: [],
    };
  },
  onLoad(options) {
    this.upImg = [];
    this.upFiles = [];
    this.linkId = options.linkId;
    this.form.id = options.linkId;
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      this.userId = getUserInfoId();
      this.form.priceUserId = this.userId;
      UserInfoApi.getUserProfile(this.userId).then(res => {
        this.form.priceUserPhone = res?.data?.phone;
        this.form.priceUserStr = res?.data?.name;
      });
    },
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i],'image')
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },

    uploadFilePromise(file, type) {
      const _this = this
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            'Authorization': 'Bearer ' + getToken(),
          },
          url: _this.baseURL + '/resource/oss/upload',
          filePath: file.url,
          name: 'file',
          formData: {
            file: file
          },
          success: (res) => {
            setTimeout(() => {
              const json = JSON.parse(res.data);
              console.log('6666---->>>,',json);
              if (type === 'image') {
                this.upImg.push(json.data?.ossId);
              }else {
                this.upFiles.push(json.data?.ossId);
              }
              resolve(res.data.data)
            }, 1000)
          }
        });
      })
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    async afterReadOther(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'success',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i],'other')
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    deletePicOther(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },

    submitForm() {
      console.log(this.form);
      this.$refs.formRef.validate().then((res) => {
        if (this.upImg.length > 0) {
          this.form.priceImg = this.upImg.join(',');
        }
        if (this.upFiles.length > 0) {
          this.form.priceFiles = this.upFiles.join(',');
        }
        PriceApi.addSupplierPrice(this.form).then(() => {
          uni.showToast({
            title: '报价成功',
            icon: 'success',
            duration: 2000
          });
          setTimeout(() => {
            uni.switchTab( {
              url: '/pages/index'
            });
          }, 2000);
        });
      }).catch((err) => {
        console.log(err);
      })
    }
  },
}
</script>

<style scoped lang="scss">
.price-box{
  margin-top: -50px;
}
</style>
